<template>
  <div id="register">
    <el-dialog title="注册" width="450px" center :visible.sync="isRegister">
      <el-form
          :model="RegisterUser"
          :rules="rules"
          status-icon
          ref="ruleForm"
          class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
              prefix-icon="el-icon-user-solid"
              placeholder="请输入账号"
              v-model="RegisterUser.username"
              maxlength="30"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              prefix-icon="el-icon-view"
              type="password"
              placeholder="请输入密码"
              v-model="RegisterUser.password"
              maxlength="30"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPass">
          <el-input
              prefix-icon="el-icon-view"
              type="password"
              placeholder="请再次输入密码"
              v-model="RegisterUser.confirmPass"
              maxlength="30"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="slideVerify">
          <center>
            <slide-verify
                ref="slideblock"
                :l="42"
                :r="10"
                :w="310"
                :h="155"
                @again="onAgain"
                @success="onSuccess"
                @fail="onFail"
                @refresh="onRefresh"
                :slider-text="text">
            </slide-verify>
            <div>{{times}}</div>
          </center>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Register" style="width:100%;">注册</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MallRegister",
  props: ["register"],
  data() {
    //图像验证码
    let validateSlid =(rule, value, callback) =>{
      value=this.isValid;
      //console.log(value)
      if (!value) {
        return callback(new Error("请通过图像验证"));
      }else{
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      }
    };
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以中文或字母开头,长度在1-30之间,允许字母数字下划线
      const userNameRule = /^[\u4E00-\u9FA5a-zA-Z0-9_]{1,30}$/;
      if (userNameRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("中文或字母开头,长度在1-30之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以数字或字母开头,长度在5-30之间,允许字母数字和下划线
      const passwordRule = /^[a-zA-Z0-9_]{5,30}$/;
      if (passwordRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(
            new Error("数字或字母开头,长度在5-30之间,允许字母数字和下划线")
        );
      }
    };
    // 确认密码的校验方法
    let validateConfirmPass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入确认密码"));
      }
      // 校验是否以密码一致
      //console.log(this.RegisterUser.password+"\n"+value)
      if (this.RegisterUser.password !== "" && value === this.RegisterUser.password) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("两次输入的密码不一致"));
      }
    };
    return {
      /**
       * @滑块验证秒数
       * */
      times:'',
      /**
       * @滑块验证
       * */
      isValid:false,
      text: '向右拖动滑块填充拼图', //滑块底部文字
      isRegister: false, // 控制注册组件是否显示
      RegisterUser: {
        username: "",
        password: "",
        confirmPass: ""
      },
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        username: [{validator: validateName, trigger: "blur"}],
        password: [{validator: validatePass, trigger: "blur"}],
        confirmPass: [{validator: validateConfirmPass, trigger: "blur"}],
        slideVerify:[{validator: validateSlid, trigger: "blur"}],
      }
    };
  },
  watch: {
    // 监听父组件传过来的register变量，设置this.isRegister的值
    register: function (val) {
      if (val) {
        this.isRegister = val;
      }
    },
    // 监听this.isRegister变量的值，更新父组件register变量的值
    isRegister: function (val) {
      if (!val) {
        this.onAgain();
        this.times="";
        this.isValid=false;
        this.$refs["ruleForm"].resetFields();
        this.$emit("fromChild", val);
      }
    }
  },
  methods: {
    Register() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate(valid => {
        //如果通过校验开始注册
        if (valid) {
          this.$axios
              .post(this.$store.state.baseURL + 'client/' +
                  this.$store.state.controller.Login + '/' + this.$store.state.mappings.signup,
                  {
                    cid: -1,
                    creattime: "",
                    name: this.RegisterUser.username,
                    pic: {picid: 1},
                    age: "",
                    sex: "",
                    vip: "",
                    qq: "",
                    wx: "",
                    email: "",
                    describe: {iid: 1},
                    password: this.RegisterUser.password,
                    state: 1,
                    telephone: "123456789"
                  })
              .then(res => {
                // “001”代表注册成功，其他的均为失败
                if (res.data === "注册==>成功") {
                  // 隐藏注册组件
                  this.isRegister = false;
                  // 弹出通知框提示注册成功信息
                  this.notifySucceed(res.data);
                } else {
                  // 弹出通知框提示注册失败信息
                  this.notifyError(res.data);
                }
              })
              .catch(err => {
                return Promise.reject(err);
              });
        } else {
          return false;
        }
      });
    },
    onSuccess(times) {
      this.isValid=true;
      this.times='耗时'+(times / 1000).toFixed(1)+'s';
    },
    onFail() {
      this.isValid=false;
    },
    onRefresh() {
      this.isValid=false;
    },
    onAgain() {
      //console.log('检测到非人为操作的哦！');
      // 刷新
      this.$refs.slideblock.reset();
    },
  }
}
</script>

<style scoped>

</style>